<?php

/**
 * 夏日葵电商系统
 * http://www.xiarikui.com
 */

namespace Xcx\Controller;

use Think\Controller;

class XcxBaseController extends Controller {

    public $user = array();
    public $user_id = 0;
    public $session_id;
    public $weixin_config;
    public $cateTree = array();

    /**
     * 初始化操作
     */
    public function _initialize() {
        date_default_timezone_set("PRC");
        $token = I('post.token');
        if($token){
            $res = decrypt_token($token);
            $this->user_id = $res['user_id'] ? $res['user_id'] : 0;
            session('user_id' , $this->user_id);
            $info = M('users')->where('user_id = '.$this->user_id . ' and is_lock = 0')->find();
            $this->user = $info;
        }else{
            //$this->user_id =1;
            //session('user_id' , 1);
            session('user_id' , 0);
        }
//        $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
//        $allow_origin = array(
//            'http://b2c.xiarikui.cn',
//            'https://open.weixin.qq.com'
//        );
//        if (in_array($origin, $allow_origin)) {
//            header('Access-Control-Allow-Origin:' . $origin);
//        }
//        header('Access-Control-Allow-Origin:*');
//        $this->session_id = session_id(); // 当前的 session_id       
//        define('SESSION_ID', $this->session_id); //将当前的session_id保存为常量，供其它方法调用
//        // 判断当前用户是否手机                
//        if (isMobile())
//            cookie('is_mobile', '1', 3600);
//        else
//            cookie('is_mobile', '0', 3600);
//
//        //获取微信配置
//        $wechat_list = M('wx_user')->select();
//        //微信浏览器
//        if (strstr($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') && $wechat_list[0]['wait_access']) {
//            $wechat_config = $wechat_list[0];
//            $this->weixin_config = $wechat_config;
//            $this->assign('wechat_config', $wechat_config); // 微信配置
//            if ($wechat_config && !$_SESSION['openid']) {
//                //去授权获取openid
//                $wxuser = $this->GetOpenid();
//                //获取用户昵称
//
//                session('subscribe', $wxuser['subscribe']); // 当前这个用户是否关注了微信公众号
//                //微信自动登录
//                $data = array(
//                    'openid' => $wxuser['openid'], //支付宝用户号
//                    'oauth' => 'weixin',
//                    'nickname' => trim($wxuser['nickname']) ? trim($wxuser['nickname']) : '微信用户',
//                    'sex' => $wxuser['sex'],
//                    'head_pic' => $wxuser['headimgurl'],
//                );
//
//                $userModel = new UserModel();
//                $data = $userModel->thirdLogin($data);
//
//                if ($data['status'] == 1) {
//                    session('user', $data['result']);
//                    setcookie('user_id', $data['result']['user_id'], null, '/');
//                    setcookie('is_distribut', $data['result']['is_distribut'], null, '/');
//                    setcookie('uname', $data['result']['nickname'], null, '/');
//
//                    // 登录后将购物车的商品的 user_id 改为当前登录的id
//                    M('cart')->where("session_id = '{$this->session_id}'")->save(array('user_id' => $data['result']['user_id']));
//                }
//            }
//
//            // 微信Jssdk 操作类 用分享朋友圈 JS            
//            $jssdk = new \Mobile\Model\WxModel($this->weixin_config['appid'], $this->weixin_config['appsecret']);
//            $signPackage = $jssdk->GetSignPackage();
//            $this->assign('signPackage', $signPackage);
//        }
//        $this->publicAssign();
    }

    public function jsonReturn($code, $msg = '',$data = ''){
        $info['code'] = $code ?  200 : 400;
        $info['msg'] = $msg;
        $info['result'] = $data;
        exit(json_encode($info));
    }

    /**
     * 保存公告变量到 smarty中 比如 导航 
     */
    public function publicAssign() {
        $xiarikui_config = array();
        $xrk_config = M('config')->cache(true, XIARIKUI_CACHE_TIME)->select();
        foreach ($xrk_config as $k => $v) {
            if ($v['name'] == 'hot_keywords') {
                $xiarikui_config['hot_keywords'] = explode('|', $v['value']);
            }
            $xiarikui_config[$v['inc_type'] . '_' . $v['name']] = $v['value'];
        }
        $this->configArr = $xiarikui_config;
        $this->assign('xiarikui_config', $xiarikui_config);
    }

    // 网页授权登录获取 OpendId
    public function GetOpenid() {
        if ($_SESSION['openid'])
            return $_SESSION['openid'];
        //通过code获得openid
        if (!isset($_GET['code'])) {
            //触发微信返回code码
            //$baseUrl = urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING']);
            $baseUrl = urlencode($this->get_url());
            $url = $this->__CreateOauthUrlForCode($baseUrl); // 获取 code地址
            Header("Location: $url"); // 跳转到微信授权页面 需要用户确认登录的页面
            exit();
        } else {
            // 上面跳转, 这里跳了回来
            //获取code码，以获取openid
            $code = $_GET['code'];
            $data = $this->getOpenidFromMp($code);
            $data2 = $this->GetUserInfo($data['access_token'], $data['openid']);
            $data['nickname'] = $data2['nickname'];
            $data['sex'] = $data2['sex'];
            $data['headimgurl'] = $data2['headimgurl'];
            $data['subscribe'] = $data2['subscribe'];
            $_SESSION['openid'] = $data['openid'];
            return $data;
        }
    }

    /**
     * 获取当前的url 地址
     * @return type
     */
    private function get_url() {
        $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
        $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
        $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
        $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self . (isset($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : $path_info);
        return $sys_protocal . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . $relate_url;
    }

    /**
     *
     * 通过code从工作平台获取openid机器access_token
     * @param string $code 微信跳转回来带上的code
     *
     * @return openid
     */
    public function GetOpenidFromMp($code) {
        //通过code换取网页授权access_token  和 openid
        $url = $this->__CreateOauthUrlForOpenid($code);
        $ch = curl_init(); //初始化curl        
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置超时
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $res = curl_exec($ch); //运行curl，结果以jason形式返回            
        $data = json_decode($res, true); //取出openid access_token                
        curl_close($ch);

        return $data;
    }

    /**
     *
     * 通过access_token openid 从工作平台获取UserInfo      
     * @return openid
     */
    public function GetUserInfo($access_token, $openid) {
        // 获取用户 信息
        $url = $this->__CreateOauthUrlForUserinfo($access_token, $openid);
        $ch = curl_init(); //初始化curl        
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置超时
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $res = curl_exec($ch); //运行curl，结果以jason形式返回            
        $data = json_decode($res, true); //取出openid access_token                
        curl_close($ch);

        // 获取看看用户是否关注了 你的微信公众号， 再来判断是否提示用户 关注
        $access_token2 = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token2&openid=$openid";
        $subscribe_info = httpRequest($url, 'GET');
        $subscribe_info = json_decode($subscribe_info, true);
        $data['subscribe'] = $subscribe_info['subscribe'];

        return $data;
    }

    public function getAccessToken() {
        //判断是否过了缓存期
        $wechat = M('wx_user')->find();
        $expire_time = $wechat['web_expires'];
        if ($expire_time > time()) {
            return $wechat['web_access_token'];
        }
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$wechat[appid]}&secret={$wechat[appsecret]}";
        $return = httpRequest($url, 'GET');
        $return = json_decode($return, 1);
        $web_expires = time() + 7000; // 提前200秒过期
        M('wx_user')->where(array('id' => $wechat['id']))->save(array('web_access_token' => $return['access_token'], 'web_expires' => $web_expires));
        return $return['access_token'];
    }

    /**
     *
     * 构造获取code的url连接
     * @param string $redirectUrl 微信服务器回跳的url，需要url编码
     *
     * @return 返回构造好的url
     */
    private function __CreateOauthUrlForCode($redirectUrl) {
        $urlObj["appid"] = $this->weixin_config['appid'];
        $urlObj["redirect_uri"] = "$redirectUrl";
        $urlObj["response_type"] = "code";
//        $urlObj["scope"] = "snsapi_base";
        $urlObj["scope"] = "snsapi_userinfo";
        $urlObj["state"] = "STATE" . "#wechat_redirect";
        $bizString = $this->ToUrlParams($urlObj);
        return "https://open.weixin.qq.com/connect/oauth2/authorize?" . $bizString;
    }

    /**
     *
     * 构造获取open和access_toke的url地址
     * @param string $code，微信跳转带回的code
     *
     * @return 请求的url
     */
    private function __CreateOauthUrlForOpenid($code) {
        $urlObj["appid"] = $this->weixin_config['appid'];
        $urlObj["secret"] = $this->weixin_config['appsecret'];
        $urlObj["code"] = $code;
        $urlObj["grant_type"] = "authorization_code";
        $bizString = $this->ToUrlParams($urlObj);
        return "https://api.weixin.qq.com/sns/oauth2/access_token?" . $bizString;
    }

    /**
     *
     * 构造获取拉取用户信息(需scope为 snsapi_userinfo)的url地址     
     * @return 请求的url
     */
    private function __CreateOauthUrlForUserinfo($access_token, $openid) {
        $urlObj["access_token"] = $access_token;
        $urlObj["openid"] = $openid;
        $urlObj["lang"] = 'zh_CN';
        $bizString = $this->ToUrlParams($urlObj);
        return "https://api.weixin.qq.com/sns/userinfo?" . $bizString;
    }

    /**
     *
     * 拼接签名字符串
     * @param array $urlObj
     *
     * @return 返回已经拼接好的字符串
     */
    private function ToUrlParams($urlObj) {
        $buff = "";
        foreach ($urlObj as $k => $v) {
            if ($k != "sign") {
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }

}
